﻿// IPC Library
// Interprocess Communication Library
// Copyright(C)2008 Bill Tudor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace IPCLibrary
{
	internal class SharedMemoryStream : Stream
	{
		private SharedMemory _memoryObject;
		private long _position;

		public SharedMemoryStream(SharedMemory memoryObject)
		{
			_memoryObject = memoryObject;
		}
		public override void Close()
		{
			_memoryObject.Dispose();
			base.Close();
		}
		public override bool CanRead
		{
			get { return true; }
		}
		public override bool CanSeek
		{
			get { return true; }
		}
		public override bool CanWrite
		{
			get { return true; }
		}
		public override void Flush()
		{
			;
		}
		public override long Length
		{
			get { return _memoryObject.Size; }
		}

		public override long Position
		{
			get {return _position;}
			set	{_position = value;}
		}
		public override long Seek(long offset, SeekOrigin origin)
		{
			switch (origin)
			{
				case SeekOrigin.Begin:
					_position = offset;
					break;
				case SeekOrigin.Current:
					_position = _position + offset;
					break;
				case SeekOrigin.End:
					_position = _memoryObject.Size - offset;
					break;
			}
			return _position;
		}
		public override void SetLength(long value)
		{
			throw new IPCException("Unable to set length of shared memory stream.", new NotImplementedException());
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			int result = _memoryObject.ReadBytes(buffer, offset, (int)_position, count);
			Position += count;
			return result;
		}
		public override void Write(byte[] buffer, int offset, int count)
		{
			_memoryObject.WriteBytes(buffer, offset, (int) _position, count);
			_position += count;
		}
	}
}
